<template>
  <div class="recognition-records">
    

    <!-- 搜索和筛选区域 -->
    <el-card class="search-section">
      <el-row :gutter="16" class="search-filters">
        <el-col :span="6">
          <el-form-item label="设备筛选:">
            <el-select v-model="filters.deviceId" @change="handleFilterChange" placeholder="全部设备" clearable>
              <el-option label="全部设备" value="" />
              <el-option 
                v-for="device in devices" 
                :key="device.deviceId" 
                :label="device.deviceName" 
                :value="device.deviceId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="6">
          <el-form-item label="应用筛选:">
            <el-select v-model="filters.appId" @change="handleFilterChange" placeholder="全部应用" clearable>
              <el-option label="全部应用" value="" />
              <el-option 
                v-for="app in applications" 
                :key="app.appId" 
                :label="app.appName" 
                :value="app.appId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="6">
          <el-form-item label="任务类型:">
            <el-select v-model="filters.taskType" @change="handleFilterChange" placeholder="全部类型" clearable>
              <el-option label="全部类型" value="" />
              <el-option label="定时任务" value="定时" />
              <el-option label="手动识别" value="手动" />
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="6">
          <el-form-item label="预警状态:">
            <el-select v-model="filters.danger" @change="handleFilterChange" placeholder="全部状态" clearable>
              <el-option label="全部状态" value="" />
              <el-option label="有预警" value="1" />
              <el-option label="无预警" value="0" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="16" class="search-filters">
        <el-col :span="6">
          <el-form-item label="时间范围:">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="handleDateChange"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>

    <!-- 记录列表 -->
    <el-card class="records-section">
      <template #header>
        <div class="records-header">
          <h2>识别记录列表</h2>
          <div class="records-stats">
            <el-tag type="info">总记录: {{ pagination.total }}</el-tag>
            <el-tag type="danger">预警记录: {{ dangerCount }}</el-tag>
          </div>
        </div>
      </template>

      <el-table 
        :data="records" 
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        :row-class-name="tableRowClassName"
      >
        <el-table-column prop="recordId" label="记录ID" width="100">
          <template #default="{ row }">
            {{ row.recordId || '无' }}
          </template>
        </el-table-column>
        <el-table-column prop="deviceId" label="设备名称" width="120">
          <template #default="{ row }">
            {{ row.deviceId ? getDeviceName(row.deviceId) : '无' }}
          </template>
        </el-table-column>
        <el-table-column label="输入图片" width="120">
          <template #default="{ row }">
            <div class="image-container">
              <el-image
                v-if="row.inputImg"
                :src="getImageUrl(row.inputImg)"
                :preview-src-list="[getImageUrl(row.inputImg)]"
                preview-teleported="true"
                class="thumbnail"
                fit="cover"
              />
              <el-image
                v-if="row.outputImg"
                :src="getImageUrl(row.outputImg)"
                :preview-src-list="[getImageUrl(row.outputImg)]"
                class="thumbnail"
                fit="cover"
              />
              <span v-if="!row.inputImg && !row.outputImg">无</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="识别结果" width="150">
          <template #default="{ row }">
            <el-tooltip :content="getDetectionSummary(row.recResult)" placement="top">
              <div class="result-summary">
                <span v-if="getDetectionSummary(row.recResult)">
                  {{ getDetectionSummary(row.recResult) }}
                </span>
                <span v-else>无</span>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="置信度" width="100">
          <template #default="{ row }">
            <el-tag 
              :type="getConfidenceType(row.confidence)"
              size="small"
            >
              {{ row.confidence ? (row.confidence * 100).toFixed(1) + '%' : '无' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="预警状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.danger === 1 ? 'danger' : 'success'">
              {{ row.danger === 1 ? '预警' : '正常' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="taskType" label="任务类型" width="100">
          <template #default="{ row }">
            {{ row.taskType || '无' }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="viewDetails(row)">
              详情
            </el-button>
            <el-button type="danger" size="small" @click="deleteRecord(row.recordId)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情模态框 -->
    <el-dialog
      v-model="showDetailModal"
      title="识别记录详情"
      width="800px"
      :before-close="closeDetailModal"
    >
      <div v-if="selectedRecord" class="detail-content">
        <el-card class="detail-section">
          <template #header>
            <h4>基本信息</h4>
          </template>
          <el-row :gutter="16">
            <el-col :span="12">
              <el-descriptions :column="1" border>
                <el-descriptions-item label="记录ID">
                  {{ selectedRecord.recordId || '无' }}
                </el-descriptions-item>
                <el-descriptions-item label="设备名称">
                  {{ selectedRecord.deviceId ? getDeviceName(selectedRecord.deviceId) : '无' }}
                </el-descriptions-item>
                <el-descriptions-item label="任务类型">
                  {{ selectedRecord.taskType || '无' }}
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
            <el-col :span="12">
              <el-descriptions :column="1" border>
                <el-descriptions-item label="处理状态">
                  {{ selectedRecord.processStatus || '无' }}
                </el-descriptions-item>
                <el-descriptions-item label="创建时间">
                  {{ selectedRecord.createTime ? formatDate(selectedRecord.createTime) : '无' }}
                </el-descriptions-item>
                <el-descriptions-item label="预警状态">
                  <el-tag :type="selectedRecord.danger === 1 ? 'danger' : 'success'">
                    {{ selectedRecord.danger === 1 ? '预警' : '正常' }}
                  </el-tag>
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
          </el-row>
        </el-card>
        
        <el-card class="detail-section">
          <template #header>
            <h4>识别结果</h4>
          </template>
          <el-input
            v-model="formattedRecResult"
            type="textarea"
            :rows="8"
            readonly
            class="result-detail"
          />
        </el-card>
        
        <el-card v-if="selectedRecord.inputImg" class="detail-section">
          <template #header>
            <h4>输入图片</h4>
          </template>
          <el-image
            :src="getImageUrl(selectedRecord.inputImg)"
            :preview-src-list="[getImageUrl(selectedRecord.inputImg)]"
            class="detail-image"
            fit="contain"
          />
        </el-card>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getRecordList, deleteRecRecord } from '@/api/agriculture/xctl/recognition'
import deviceAPI from '@/api/agriculture/xctl/device'
import appAPI from '@/api/agriculture/xctl/appManage'
import { getImageUrlFromPath } from '@/utils/image'

// 响应式数据
const records = ref([])
const devices = ref([])
const applications = ref([])
const loading = ref(false)
const showDetailModal = ref(false)
const selectedRecord = ref(null)
const dateRange = ref([])

// 筛选条件
const filters = reactive({
  deviceId: '',
  appId: '',
  taskType: '',
  danger: '',
  startDate: '',
  endDate: ''
})

// 分页信息
const pagination = reactive({
  pageNum: 1,
  pageSize: 20,
  total: 0
})

// 计算预警记录数量
const dangerCount = computed(() => {
  return records.value.filter(record => record.danger === 1).length
})

// 计算格式化的识别结果
const formattedRecResult = computed(() => {
  if (!selectedRecord.value?.recResult) return '无结果'
  return formatRecResult(selectedRecord.value.recResult)
})

// 获取设备列表
const fetchDevices = async () => {
  try {
    const response = await deviceAPI.getDeviceList()
    if (response.code === 200) {
      devices.value = response.rows || []
    }
  } catch (error) {
    console.error('获取设备列表失败:', error)
    ElMessage.error('获取设备列表失败')
  }
}

// 获取应用列表
const fetchApplications = async () => {
  try {
    const response = await appAPI.getAppList()
    if (response.code === 200) {
      applications.value = response.rows || []
    }
  } catch (error) {
    console.error('获取应用列表失败:', error)
    ElMessage.error('获取应用列表失败')
  }
}

// 处理筛选条件变化
const handleFilterChange = () => {
  pagination.pageNum = 1
  fetchRecords()
}

// 处理日期范围变化
const handleDateChange = (dates) => {
  if (dates && dates.length === 2) {
    filters.startDate = dates[0]
    filters.endDate = dates[1]
  } else {
    filters.startDate = ''
    filters.endDate = ''
  }
  handleFilterChange()
}

// 获取识别记录列表
const fetchRecords = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      orderByColumn: 'create_time',
      isAsc: 'desc',
      ...filters
    }
    
    const response = await getRecordList(params)
    if (response.code === 200) {
      records.value = response.rows || []
      pagination.total = response.total || 0
    } else {
      ElMessage.error(response.msg || '获取识别记录失败')
    }
  } catch (error) {
    console.error('获取识别记录失败:', error)
    ElMessage.error('获取识别记录失败')
  } finally {
    loading.value = false
  }
}

// 获取设备名称
const getDeviceName = (deviceId) => {
  const device = devices.value.find(d => d.deviceId === deviceId)
  return device ? device.deviceName : `设备${deviceId}`
}

// 获取图片URL
const getImageUrl = (imagePath) => {
  return getImageUrlFromPath(imagePath)
}

// 获取检测结果摘要
const getDetectionSummary = (recResult) => {
  if (!recResult) return ''
  try {
    const result = JSON.parse(recResult)
    if (result.detections && result.detections.length > 0) {
      const detection = result.detections[0]
      return `检测到: ${detection.class_name || '未知'}`
    }
    return '无'
  } catch (error) {
    return '解析失败'
  }
}

// 获取置信度样式类（保留兼容性）
const getConfidenceClass = (confidence) => {
  if (!confidence) return ''
  if (confidence >= 0.8) return 'high'
  if (confidence >= 0.5) return 'medium'
  return 'low'
}

// 获取置信度标签类型（Element Plus）
const getConfidenceType = (confidence) => {
  if (!confidence) return ''
  if (confidence >= 0.8) return 'success'
  if (confidence >= 0.5) return 'warning'
  return 'danger'
}

// 表格行样式
const tableRowClassName = ({ row }) => {
  return row.danger === 1 ? 'danger-row' : ''
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '无'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 格式化识别结果
const formatRecResult = (recResult) => {
  if (!recResult) return '无'
  try {
    return JSON.stringify(JSON.parse(recResult), null, 2)
  } catch (error) {
    return recResult
  }
}

// 查看详情
const viewDetails = (record) => {
  selectedRecord.value = record
  showDetailModal.value = true
}

// 关闭详情模态框
const closeDetailModal = () => {
  showDetailModal.value = false
  selectedRecord.value = null
}

// 显示图片模态框
const openImageModal = (imageUrl) => {
  currentImage.value = imageUrl
  showImageModal.value = true
}

// 关闭图片模态框
const closeImageModal = () => {
  showImageModal.value = false
  currentImage.value = ''
}

// 删除记录
const deleteRecord = async (recordId) => {
  try {
    await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await deleteRecRecord(recordId)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchRecords()
    } else {
      ElMessage.error('删除失败: ' + response.msg)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除记录失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 切换页面
const changePage = (page) => {
  if (page < 1 || page > Math.ceil(pagination.total / pagination.pageSize)) {
    return
  }
  pagination.pageNum = page
  fetchRecords()
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageNum = 1
  fetchRecords()
}

// 处理当前页变化
const handleCurrentChange = (page) => {
  pagination.pageNum = page
  fetchRecords()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchDevices()
  fetchApplications()
  fetchRecords()
})
</script>

<style scoped>
.recognition-records {
  padding: 16px;
}

.page-header {
  margin-bottom: 16px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.page-description {
  color: #6b7280;
  margin: 0;
}

.search-section {
  margin-bottom: 16px;
}

.search-filters {
  align-items: flex-end;
}

.records-section {
  margin-bottom: 16px;
}

.records-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.records-header h2 {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.records-stats {
  display: flex;
  gap: 16px;
}

.image-container {
  display: flex;
  gap: 8px;
  align-items: center;
}

.thumbnail {
  width: 50px;
  height: 50px;
  border-radius: 4px;
  cursor: pointer;
}

.result-summary {
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.detail-section {
  margin-bottom: 16px;
}

.detail-image {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
}

/* Element Plus 表格行样式 */
:deep(.el-table .danger-row) {
  background-color: #fef2f2;
}

:deep(.el-table .danger-row:hover > td) {
  background-color: #fecaca !important;
}

/* 图片预览模态框样式 */
:deep(.el-image-viewer__wrapper) {
  z-index: 9999 !important;
  position: fixed;
}

:deep(.el-image-viewer__mask) {
  z-index: 9998 !important;
  position: fixed;
}

/* 确保图片预览在所有内容之上 */
:deep(.el-image-viewer__img) {
  z-index: 10000 !important;
}

:deep(.el-image-viewer__actions) {
  z-index: 10001 !important;
}

:deep(.el-image-viewer__close) {
  z-index: 10001 !important;
}

:deep(.el-image-viewer__btn) {
  z-index: 10001 !important;
}


</style>